const express = require('express');
const router = express.Router();
const moment = require('moment');
const mqtt = require('mqtt');

// 仪表apk定制开发商标识
const apkSupporterCode = "iot001"

const productCode = "uykc7e2a"
const deviceCode = "12345"

// const clientId = `${apkSupporterCode}_${deviceCode}`
const clientId = `gtbxmhasce`
const username = "admin"
const password = "nttieren0513"

// 连接选项
const options = {
    clean: true, // true: 清除会话, false: 保留会话
    connectTimeout: 4000, // 超时时间
    clientId,
    username,
    password,
    keepalive: 60,
    will: {
        topic: `will-msg/${clientId}`,
        payload: 'offline',
        qos: 2,
        retain: false
    }
}

// const connectUrl = 'wss://iot.ironmanapi.com:8084/mqtt'
const connectUrl = 'wss://test.ironmanapi.com:8084/mqtt'
const client = mqtt.connect(connectUrl, options)

router.post('/', (req, res) => {
    req.body.ts = moment().format('YYYYMMDDHHmmssSSS')
    client.publish(`thing/up/property/${productCode}/${deviceCode}`, JSON.stringify(req.body), {qos: 1});
    res.json({'code': 1, 'msg': 'ok'})
})

router.post('/plc', (req, res) => {
    const ts = moment().format('YYYY-MM-DDTHH:mm:ss.SSS');
    console.log(ts)
    req.body.ts = ts
    client.publish(`iot_s/use/${deviceCode}/JINSU/fmt/json`, JSON.stringify(req.body), {qos: 1});
    res.json({'code': 1, 'msg': 'ok'})
})

module.exports = router
